package com.example.navigation.views

import android.content.Context
import android.util.Log
import android.view.View
import android.widget.Toast
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Poi
import com.amap.api.navi.AmapNaviPage
import com.amap.api.navi.AmapNaviParams
import com.amap.api.navi.AmapNaviType
import com.amap.api.navi.AmapPageType
import com.amap.api.navi.INaviInfoCallback
import com.amap.api.navi.enums.PageType
import com.amap.api.navi.model.AMapNaviLocation
import com.example.navigation.api.navigation.LineSegment
import com.example.navigation.api.navigation.Point
import com.example.navigation.api.navigation.PointIndex
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * Created with IntelliJ IDEA.
 * @Author: Liao Run
 * @Date: 2024-06-28 1:50
 * @Description:
 **/
class MyNavInfoCallback(
    private val needNavigationRouter: LineSegment,
    private var endIndex: Int,
    val context: Context
) : INaviInfoCallback {

    private var useClickExit = true
    override fun onInitNaviFailure() {
    }

    override fun onGetNavigationText(p0: String?) {
    }

    override fun onLocationChange(p0: AMapNaviLocation?) {
    }

    override fun onArriveDestination(p0: Boolean) {
        Log.e(this.toString(), "onArriveDestination: $p0")
        useClickExit = false
        //退出导航组件
        AmapNaviPage.getInstance().exitRouteActivity()
    }

    override fun onStartNavi(p0: Int) {
    }

    override fun onCalculateRouteSuccess(p0: IntArray?) {
    }

    override fun onCalculateRouteFailure(p0: Int) {
    }

    override fun onStopSpeaking() {
    }

    override fun onReCalculateRoute(p0: Int) {
    }


    override fun onExitPage(pageType: Int) {

        if (pageType == PageType.COMPONENT) {
            return
        }
        if (useClickExit) {
            return
        }

        CoroutineScope(Dispatchers.Default).launch {
            // 等待上一个界面摧毁
            while (AmapNaviPage.getInstance().isNaviPage) {
                delay(10)
            }
            // 默认下次退出是用户点击退出，在到达目的地是变为false,表示是程序调用的退出
            useClickExit = true

            // 开始下一段导航
            // 添加16个途经点信息
            val waysPoiIds: MutableList<Poi> = arrayListOf()
            for (i in 1..16) {
                val point: Point = try {
                    needNavigationRouter[endIndex + i * pointInterval]
                } catch (e: IndexOutOfBoundsException) {
                    // 没有更多的点需要走了，走航结束
                    if (waysPoiIds.size == 0) {
                        Toast.makeText(context, "本次导航完成！", Toast.LENGTH_LONG).show()
                        return@launch
                    }
                    // 还有一小段路没走
                    break
                }
                waysPoiIds.add(
                    Poi(
                        "途经点${i}",
                        LatLng(point[PointIndex.latitude.ordinal].toDouble(), point[PointIndex.longitude.ordinal].toDouble()),
                        null
                    )
                )
            }

            endIndex += 17 * pointInterval
            val endPoint = try {
                needNavigationRouter[endIndex]
            } catch (e: IndexOutOfBoundsException) {
                // 没有更多的路需要走了,最后一个点就终点
                endIndex = needNavigationRouter.size
                needNavigationRouter.last()
            }
            // 终点信息
            val end = Poi(
                "当前终点",
                LatLng(endPoint[PointIndex.latitude.ordinal].toDouble(), endPoint[PointIndex.longitude.ordinal].toDouble()),
                null
            )

            // POI算路
            // POI算路
            // 组件参数配置
            val params = AmapNaviParams(null, waysPoiIds, end, AmapNaviType.DRIVER, AmapPageType.NAVI)
            // 启动组件
            AmapNaviPage.getInstance().showRouteActivity(context, params, this@MyNavInfoCallback)
        }
    }

    override fun onStrategyChanged(p0: Int) {
    }

    override fun onArrivedWayPoint(p0: Int) {
    }

    override fun onMapTypeChanged(p0: Int) {
    }

    override fun onNaviDirectionChanged(p0: Int) {
    }

    override fun onDayAndNightModeChanged(p0: Int) {
    }

    override fun onBroadcastModeChanged(p0: Int) {
    }

    override fun onScaleAutoChanged(p0: Boolean) {
    }

    override fun getCustomMiddleView(): View? {
        return null
    }

    override fun getCustomNaviView(): View? {
        return null
    }

    override fun getCustomNaviBottomView(): View? {
        return null
    }


}